package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CatalogService catalogService;

    @GetMapping("/viewCart")
    public String viewCart(HttpSession session){
        Account account = (Account) session.getAttribute("account");
        if(account==null){
            return "account/signonForm";
        }else{
            String username = account.getUsername();
            List<CartItem> cart =(List<CartItem>) session.getAttribute("cart");
            if(cart == null){
                cart = new ArrayList<CartItem>();
                //修改
            }
            cart = cartService.selectItemByUsername(username);
            session.setAttribute("cart",cart);
            Order order = new Order();
            order.initOrder(account,cart);
            session.setAttribute("tempOrder",order);
            System.out.println("查看购物车页面");
            System.out.println(order.getOrderId());
            System.out.println(order.getTotalPrice());
//            System.out.println(order.getLineItems().get(0).getQuantity());
            return "cart/cart";
        }
    }

    @GetMapping("/removeItem")
    public String removeItemFromCart(HttpSession session, Model model, @RequestParam("workingItemId") String workingItemId){
        Account account = (Account) session.getAttribute("account");
        if(account==null){
            session.setAttribute("message", "Please sign in first.");
            model.addAttribute("message", "Please sign in first.");
            return "common/error";
        }else{
            String username = account.getUsername();
            CartItem cartItem = cartService.getCartItemByUsernameAndItemId(username,workingItemId);
            if(cartItem==null){
                session.setAttribute("message", "Attempted to remove all null CartItem from Cart.");
                model.addAttribute("message", "Attempted to remove all null CartItem from Cart.");
                return "common/error";
            }else{
                cartService.removeCartItemByUsernameAndItemId(username,workingItemId);
                List<CartItem> cart = cartService.selectItemByUsername(username);
                session.setAttribute("cart",cart);
                model.addAttribute("cart",cart);
                Order order = new Order();
                order.initOrder(account,cart);
                session.setAttribute("tempOrder",order);
                System.out.println("移出购物车");
                System.out.println(order.getOrderId());
                System.out.println(order.getTotalPrice());
                return "cart/cart";
            }
        }
    }

    @PostMapping("/updateCart")
    public void updateCartQuantities(HttpServletResponse resp, @RequestParam("itemId") String itemId, @RequestParam("quantity") String quantity, HttpSession session, Model model) throws IOException {
        int quantity1 = Integer.parseInt(quantity);
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        cartService.updateItemByItemIdAndQuantity(username,itemId,quantity1);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        CartItem cartItem=cartService.getCartItemByUsernameAndItemId(username,itemId);
        System.out.println(cartItem.getTotalCost());
        result.setCode(12);
        String str1=cartItem.getTotalCost().toString();
        System.out.println(str1);
        result.setMsg(str1);
        Order order = new Order();
        List<CartItem> cart = cartService.selectItemByUsername(username);
        session.setAttribute("cart",cart);
        order.initOrder(account,cart);
        System.out.println(order.getOrderId());
        System.out.println(order.getTotalPrice());
        session.setAttribute("tempOrder",order);
        System.out.println("更新购物车");
        System.out.println(order.getOrderId());
        System.out.println(order.getTotalPrice());
//        System.out.println("更新购物车"+cartItem.getTotalCost().toString());
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart(HttpSession session,@RequestParam("workingItemId") String workingItemId){
        Account account = (Account) session.getAttribute("account");
        if(account == null){
            return "account/signonForm";
        }else{
            String userId = account.getUsername();
            CartItem cartItem = cartService.getCartItemByUsernameAndItemId(userId,workingItemId);
            if(cartItem!=null){
                if(!cartItem.isPay()){
                    cartService.incrementItemByUsernameAndItemId(userId,workingItemId);
                }else{
                    cartService.updateItemByItemIdAndPay(userId,workingItemId,false);
                    cartService.updateItemByItemIdAndQuantity(userId,workingItemId,1);

                }
            }else{
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cartService.addItemByUsernameAndItemId(userId,item,isInStock);
            }
            List<CartItem> cart = cartService.selectItemByUsername(userId);
            session.setAttribute("cart",cart);
            Order order = new Order();
            order.initOrder(account,cart);
            session.setAttribute("tempOrder",order);
            System.out.println("加入购物车");
            System.out.println(order.getOrderId());
            System.out.println(order.getTotalPrice());
            return "cart/cart";
        }
    }
}
